package org.yuchen.tag;

import java.util.Collection;
import java.util.Iterator;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyContent;
import javax.servlet.jsp.tagext.BodyTagSupport;

/**
 * this is a iteration tag.
 * 
 * @author neil
 *
 */
public class ForEach extends BodyTagSupport{
	private static final long serialVersionUID = -3486361905031497757L;
	private String id;
	private String collection;
	@SuppressWarnings("unchecked")
	private Iterator iter;
	
	//������ǩ��ִ��  
	@Override
	public int doAfterBody() throws JspException {
		if(iter.hasNext()){
			pageContext.setAttribute(id, iter.next());
			return EVAL_BODY_AGAIN;// �����л��ж�����ѭ��ִ�б�ǩ��  
		}
		return SKIP_BODY;//����꼯�Ϻ�����ǩ�壬����doEndTag()������  
	}

	//���������ǩִ��  
	@Override
	public int doEndTag() throws JspException {
		System.out.println("doEndTag...");  
		return EVAL_PAGE;  
	}

	//�˷������ƹ�ᱻִ��  
	@Override
	public void doInitBody() throws JspException {
		System.out.println("doInitBody...");  
		super.doInitBody();
	}

	//������ʼ��ǩִ�С�step 1.
	@Override
	public int doStartTag() throws JspException {
		System.out.println("doStartTag...");  
		
		Collection coll = (Collection) pageContext.findAttribute(collection);
		//���δ�ҵ�ָ���ļ��ϣ����ô����ǩ�壬ֱ�ӵ���doEndTag();
		if(collection == null || collection.isEmpty()){
			return SKIP_BODY;
		}
		
		iter = coll.iterator();
		pageContext.setAttribute(id, iter.next());
		
		//��ʾ�����е�������д����ǩ�壬�ƹ�setBodyContent()��doInitBody();
		//����һ��Ҫ����EVAL_BODY_INCLUDE,�����ǩ������ݲ�����ҳ������ʾ��
		return EVAL_BODY_INCLUDE;
	}

	//��doInitBody����֮ǰִ�У������ﱻ�ƹ�ִ��  
	@Override
	public void setBodyContent(BodyContent b) {
		System.out.println("setBodyContent...");  
		super.setBodyContent(b);
	}

	public void setId(String id) {
		this.id = id;
	}

	public void setCollection(String collection) {
		this.collection = collection;
	}

}
